import scrapy

from ScrapyObject.spiders.utils.url_utils import *

'''
scrapy crawl ydat -o ydat.json
https://27.cmsp9.sbs/
'''


class YdatSpider(scrapy.Spider):
    name = "ydat"
    # 前缀
    prefix = 'https://27.'
    # 中缀
    website = 'cmsp9'
    # 后缀
    suffix = '.sbs/'
    allowed_domains = [website + '.sbs']
    start_urls = [prefix + website + suffix]

    def __init__(self):
        self.i = 0

    def parse(self, response):
        content = get_data(response)
        video_url = get_video_url_one(content)
        if len(video_url):
            self.i = self.i + 1
            yield get_video_item(id=self.i, tags='', url=response.url, name='', pUrl='', vUrl=format_url_one(video_url[0]))
        else:
            tags = response.xpath("//div[@class='title']//h3/text()").extract()
            p_url = response.xpath("//div[@class='vod-img']//a//img/@ data-original").extract()
            url = response.xpath("//div[@class='vod-txt']//a/@ href").extract()
            name = response.xpath("//div[@class='vod-txt']//a/text()").extract()
            if len(tags) and len(name) and len(url) and len(p_url):
                for i in range(len(url)):
                    self.i = self.i + 1
                    yield get_video_item(id=self.i, tags=tags[1], url=split_joint(self.prefix + self.website + self.suffix, url[i]), name=name[i], pUrl=split_joint(self.prefix + self.website + self.suffix, p_url[i]), vUrl='')
        url_list = get_url(content)
        for url in url_list:
            if url.startswith('/') and url.endswith('.html'):
                yield scrapy.Request(split_joint(self.prefix + self.website + self.suffix, url), callback=self.parse)
